package org.restql.db.resource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;

import org.apache.commons.dbcp.BasicDataSource;
import org.restql.db.resource.RequestResource;

public class AutomaticDatabaseResourceImpl extends ModifiableDatabaseResourceImpl {

	Hashtable<String, BasicDataSource> dataSources = new Hashtable<String, BasicDataSource>();
	
	public AutomaticDatabaseResourceImpl() {
		this.select = new ArrayList<String>();
		this.select.add("*");
		this.where = new ArrayList<String>();
	}

    @Override
    public Connection getConnection(RequestResource requestResource) throws SQLException {
        String jdbcUrl = "jdbc:mysql://localhost:3306/" + requestResource.getDbName();
        String connectString = jdbcUrl + "||" + requestResource.getUser() + "||" + 
        	requestResource.getPassword();
        
        BasicDataSource dataSource = null;
        if (dataSources.containsKey(connectString)) {
        	dataSource = dataSources.get(connectString);
        } else {
        	dataSource = new BasicDataSource();
        	dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        	dataSource.setUsername(requestResource.getUser());
        	dataSource.setPassword(requestResource.getPassword());
        	dataSource.setUrl(jdbcUrl);
        	dataSources.put(connectString, dataSource);
        }
        
        return dataSource.getConnection();
    }

    @Override
    public String getFromString(RequestResource requestResource) {
		return "FROM " + requestResource.getResourceName();
	}

    @Override
    public String getInsertString(RequestResource requestResource) {
		return "INSERT INTO " + requestResource.getResourceName();
	}

    @Override
	public String getUpdateString(RequestResource requestResource) {
		return "UPDATE " + requestResource.getResourceName();
	}

    public boolean reissueCredentials() {
    	return true;
    }
}
